package com.xspace.android.imcommon.http;

import com.google.gson.Gson;
import com.xspace.android.imcommon.entity.ChatMsg;
import com.xspace.android.imcommon.entity.RobotInfo;
import com.xspace.android.imcommon.utils.ImConstants;
import com.xspace.android.xafcommon.util.AppUtils;
import com.xspace.android.xafcommon.util.LogUtils;

import java.io.InputStream;

public class RobotTask implements NetworkListener {
	private String body;
	private RobotRequestResult requestResult;
    private ChatMsg info;
	public RobotTask(ChatMsg info, RobotRequestResult requestResult) {
		this.body = info.mContent;
		this.info=info;
		this.requestResult = requestResult;
	}

	@Override
	public void action(int actionCode, Object object) {
		LogUtils.i("actionCode : %s" + actionCode);
		switch (actionCode) {
		case NetworkListener.RECEIVE_STREAM:
			try {
				String result = AppUtils.parser((InputStream) object);
				LogUtils.i("fetch frienddetail response : %s" + result);
				parserContactList(result);
			} catch (Exception e) {
				this.requestResult.requestResult(info,null);
				LogUtils.i("FetchFriendsTask" + e + "");
			}
			break;
		default:
			this.requestResult.requestResult(info,null);
			break;
		}
	}

	/**
	 * 解析网络联系人列表
	 * 
	 * @param result
	 * @throws Exception
	 */
	private void parserContactList(String result) throws Exception {
		RobotInfo robot = null;
		try {
			Gson mGson = new Gson();
			robot = mGson.fromJson(result, RobotInfo.class);
		} catch (Exception e) {
			e.printStackTrace();

		}
		this.requestResult.requestResult(info,robot);
	}

	/**
	 * 发送获取网络联系人请求
	 */
	public void sendRequest() {
		ConnectorImpl conn = new ConnectorImpl(ImConstants.getRobottalkUrl(), buildFetchFriendsRequest(), this, ConnectorImpl.POST);
		System.out.println("----------------------------getRobottalkUrl:"+ImConstants.getRobottalkUrl());
		ThreadPoolWrap.getThreadPool().executeTask(conn);
	}

	// 构造获取好友请求
	private String buildFetchFriendsRequest() {
		return "{body:\"" + body + "\"}";

	}

}
